require(['gaodeMap', 'validator'], function () {
    var $formData = $('#formData');

    var polygonOrCircle;//多边形或者圆形对象
    var polygonOrCircleEditor;//多边形或者圆形编辑对象
    var mousetool;//鼠标操作插件

    var defaultConfig = {
        strokeColor: "#1791fc",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#1791fc",
        fillOpacity: 0.35,
        strokeStyle: "solid",
        strokeDasharray: [10, 5]
    };

    $formData.initForm();

    function resize() {
        $('#iCenter').height($(window).height() - $formData.outerHeight() - 10);
    }
    $(window).on('resize', resize).trigger('resize');

    var mapObj = new MapGaoDe(107.49023438, 36.24427318, 4);
    mapObj.isDoubleClickZoom(false);//设置双击不能放大地图


    mapObj.map.plugin(["AMap.MouseTool"], function () {
        mousetool = new AMap.MouseTool(mapObj.map);
        AMap.event.addListener(mousetool, 'draw', function (arg) {
            polygonOrCircle = arg.obj;
            mousetool.close();
        });
    });

    //多边形或者圆形编辑对象关闭编辑
    function polygonOrCircleEditorSave() {
        if (polygonOrCircleEditor) {
            polygonOrCircleEditor.close();
            polygonOrCircleEditor = null;
        }
    }

    AMap.event.addListener(mapObj.map, 'dblclick', function () {
        polygonOrCircleEditorSave();
    });

    //选择所属企业时触发事件
    $('#fenc_organName').on('click', function () {
        commonFun.execParentMethod('treeDialog', {
            url: '/baseOrgan/getBaseOrganList.htm',
            name: 'organName',
            idKey: 'organId',
            pIdKey: 'parentOrganId'
        }, this, function (data) {
            if (data) {
                $("#cityName").val(data.cityName);
                $("#cityId").val(data.cityId);
                $("#provinceId").val(data.provinceId);
                mapObj.map.setCity(data.cityName);
                mapObj.map.setZoom(14);
            }
        });
    });

    //新增或者修改保存
    window.saveOrUpdate = function (callBack) {
    	
    	
    	
        polygonOrCircleEditorSave();
        var result = $.validator($formData);
        if (!result) {
            return;
        }
        var params = $formData.getValues();

        if (params.fencType == 1) {
            var array = polygonOrCircle.getPath();
            $.each(array, function (i, item) {
                params["list[" + i + "].fencLgt"] = formatterDecimal(item.lng);
                params["list[" + i + "].fencLtt"] = formatterDecimal(item.lat);
            });
        } else {
            var center = polygonOrCircle.getCenter();
            params["coreLgt"] = formatterDecimal(center.lng);
            params["coreLtt"] = formatterDecimal(center.lat);
            params["coreRadius"] = polygonOrCircle.getRadius();
        }

        var url = "/electFencSet/saveBaseElectFenc.htm";//默认新增的URL
        if (currentFencId) {//如果有currentFencId，代表是修改
            url = '/electFencSet/updateBaseElectFenc.htm';
        }
        
        //@tip(用于电子围栏)
        // params["funcType"] = "FEN00001";

        // console.info(params);
        
        $.ajaxExt({
            url: url,
            data: params
        }).done(function () {
            callBack();
        });
    };

    var currentFencId;//当前电子围栏ID

    $(".fencTypeRadio").on('change', function () {
        if (this.checked) {
            clearMap();
            if (this.value == '1') {//多边形
                mousetool.polygon();
            } else {//圆形
                mousetool.circle();
            }
        }
    });

    //编辑多边形或者圆形
    $('#edit').on('click', function () {
        if (polygonOrCircle) {
            if (polygonOrCircle.CLASS_NAME == "AMap.Polygon") {
                polygonOrCircleEditor = new AMap.PolyEditor(mapObj.map, polygonOrCircle);
            } else {
                polygonOrCircleEditor = new AMap.CircleEditor(mapObj.map, polygonOrCircle);
            }
            polygonOrCircleEditor.open();
        }
    });

    var $dialog = $('#dialog');
    $('.close-btn', $dialog).on('click', function () {
        $dialog.hide();
    });
    //查看使用说明
    $('#viewDoc').on('click', function () {
        $dialog.show();
        $('#content').css({
            top: ($(window).height() - 235) / 2,
            left: ($(window).width() - 497) / 2
        });
    });

    //获取电子围栏信息
    window.getElectFence = function (fencId) {
        currentFencId = fencId;
        $.ajaxExt({
            url: "/electFencSet/getBaseElectFencById.htm",
            data: {
                fencId: fencId
            }
        }).done(function (data) {
            console.info(data);
            if(data.funcType=='异常区'){
                data.funcType='FEN00004';
            }else if(data.funcType=='投币机'){
                data.funcType='FEN00003';
            }else if(data.funcType=='电子围栏'){
                data.funcType='FEN00001';
            }
            $formData.setValues(data);
            var params = [];
            if (data.fencType == 1) {
                $.each(data.list, function (i, item) {
                    params.push([item.fencLgt, item.fencLtt]);
                    if (i == 0) {
                        mapObj.setMapCenterAndLevel(item.fencLgt, item.fencLtt, 12);
                    }
                });
                polygonOrCircle = new AMap.Polygon($.extend({
                    map: mapObj.map,
                    path: params
                }, defaultConfig));
            } else {

                polygonOrCircle = new AMap.Circle($.extend({
                    center: [data.coreLgt, data.coreLtt],// 圆心位置
                    radius: data.coreRadius
                }, defaultConfig));
                mapObj.setMapCenterAndLevel(data.coreLgt, data.coreLtt, 12);

            }
            polygonOrCircle.setMap(mapObj.map);

        });
    };

    /**
     *清除所有的数据
     * 1.currentFencId设为空
     * 2.重置表单
     * 3.清除地图上面的数据
     */
    window.clearAll = function () {
        currentFencId = null;
        reset();
        mapObj.setMapCenterAndLevel(107.49023438, 36.24427318, 4);
    };

    //清除form表单中的数据和地图上面的信息
    window.reset = function () {
        $formData.reset();
        $(':radio',$formData).prop('checked', false);
        clearMap();
//        if (currentFencId) {
//            getElectFence(currentFencId);
//        }
    };

    function formatterDecimal(val){
    	var str = val+"";
	    var re = /([0-9]+\.[0-9]{8})[0-9]*/;
	    var newVal = str.replace(re,"$1");
	    return newVal;
    }
    
    //清除地图上面的信息
    window.clearMap = function () {
        mapObj.map.clearMap();
        if (polygonOrCircle) {
            //polygonOrCircle.setMap(null);
            polygonOrCircle = null;
            polygonOrCircleEditor = null;
        }
    };
});